package test03compare;

import java.util.TreeSet;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

/**
 * @author xhw
 */
public class _TreeSet {
    //练习六：定义一个学生类里面姓名和年龄属性，通过比较器比较出来
    public static void main(String[] args) {
        //创建一个TreeSet对象
        TreeSet<Person> personSet = new TreeSet<>();

        //添加Person对象到TreeSet
        personSet.add(new Person("a11", 50));
        personSet.add(new Person("b11", 45));
        personSet.add(new Person("c22", 40));
        personSet.add(new Person("c11", 50));

        //遍历输出TreeSet中的Person对象
        for (Person person : personSet) {
            System.out.println(person);
        }
    }

}

@Setter
@Getter
@AllArgsConstructor
class Person implements Comparable<Person> {
    String name;
    int age;

    @Override
    public int compareTo(Person p1) {
        if (this.age == p1.age) {
            return this.name.compareTo(p1.name);
        } else {
            return this.age - p1.age;
        }
    }

    @Override
    public String toString() {
        return "Person{name=" + name + "--" + age + "}";
    }
}
